class DebounceTime {
    constructor(time) {
        this.timer = null;
        this.time = time || 1000 * 0.5;
    }
    run(cb) {
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(cb, this.time);
    }
}
import { formatDate } from "@utils";
import commonForm from "@components/com-form/com-form.vue";
import configTable from "@components/com-table/com-table.vue";
export default {
    name: "com-filterTable",
    components: {
        "com-form": commonForm,
        "com-table": configTable
    },
    props: {
        busCode: [Object, String], 
        formDisabled: {
            //禁止查询,修改表单
            type:Boolean,
            default:false,
        },
        title: String,
        filterFormConfig: [Array, Function],
        topOperation: Object,
        issummary: {
            type: Boolean,
            default: false
        },
        pageSizes:Array,
        topRightOperationLine: {
            type: Boolean,
            default: false
        },
        initFormData: {
            type: Object
        },
        showSearch: {
            // 是否展示查询和重置按钮
            type: Boolean,
            default: true
        },
        height: {
            //表格高度
            type: String,
        },
        tableTitle:String,
        maxHeight: {
            type: String,
            default: '590px'
        },
        tableColumn: Array,
        queryHandle: Function,
        services: String | Function,
        params: Object,
        searchEmit: {
            type: Boolean,
            default: false
        }, //默认查询按钮点击查询，特殊情况（比如附加查询条件不满足时，查询前逻辑由页面单独操作
        dataFormatHandle: Function,
        filterLabelWidth: { type: String | Number, default: "" },
        filterCol: Number,
        filterInline: {
            default: true,
            type: Boolean
        },
        labelPosition: String,
        pagination: {
            type: Boolean,
            default: true
        },
        showFormFilter: {
            type: Boolean,
            default: true
        },
        highlightCurrentRow: {
            type: Boolean,
            default: false
        },
        rowClassName: {
            type: Function
        },
        showRequestNum: {
            type: Boolean,
            default: true
        },
        spanMethod: {
            type: Function
        },
        importData: {
            type: Array // 使用外部tableData数据，
        },
        tableBorder: {
            type: Boolean,
            default: false
        },
        tableProps: {
            type: Object,
            default: () => ({})
        },
        autoLoad: {
            type: Boolean,
            default: true
        },
        tableNoWrap: {
            type: Boolean,
            default: true
        },
        beforeSearch: {
            type: Function
        },
        queryDataHandle: Function,
        resetHandle:Function,
        resetOut:Function,
        isSingleSelect: Boolean,
        dataType: String,
        closeNumber: Number, // 保留几行不折叠
        wrappers: Object
    },
    data() {
        return {
            debounce: new DebounceTime(), //查询按钮debounce
            onQueryFilterData: null,
            selectionList: [],
            filteData: { ...this.params },
            stringHandleMap: {
                resetFilterForm: () => {
                    this.resetFilterForm();
                },
                query: () => {
                    this.filterFormQueryHandle();
                },
                querys: () => {
                    //和searchEmit查询区分
                    this.filterFormQueryHandle();
                }
            },
            handleArgumentMap: {
                batchSelected: () => {
                    return this.selectionList;
                },
                filterForm: () => {
                    return this.filteData;
                }
            },
            tableData: {},
            showColl: false
        };
    },
    computed: {
        computedWrappers() {
            let wrappers = this.wrappers || {};
            return {
                collapse: (h, {dom}) => {
                    return <div style="float: left;width:100%;">
                        <com-collapse value={this.showColl} on-input={v=>this.showColl=v} hideControl={true} position="top">{dom}</com-collapse>
                    </div>
                },
                ...wrappers
            }
        },
        computedFilterFormConfig() {
            let {filterFormConfig, closeNumber, filterCol = 4} = this;
            filterFormConfig&&filterFormConfig.map(item=>{
                if (this.formDisabled) item.disabled = this.formDisabled;
            })
            if(Object.prototype.toString.call(filterFormConfig) === '[object Array]') {
                let outConfig = [];
                let maxCol = filterCol*closeNumber || 4;
                let currentCol = 0;

                if(closeNumber) {
                    outConfig = filterFormConfig.map(item => {
                        currentCol = currentCol + (item.col || 1);
                        if(currentCol>maxCol) {
                            item.slotIn = item.slotIn || 'collapse'
                        }
                        return item;
                    });
                }
                // 塞入查询重置按钮
                outConfig = [...filterFormConfig];
                const totalColl = filterFormConfig.reduce((pre, now) => {
                    return pre + (now.col||1);
                }, 0);
                let miniHandleCol = 1;
                let handleCol = filterCol; // 默认占一整行
                const rest = (closeNumber ? maxCol : totalColl) % filterCol;
                if(filterCol >= 5) {
                    miniHandleCol = 2;
                }
                if(filterCol - rest >= miniHandleCol ) {
                    handleCol = filterCol - rest;
                }
                const handleConfig = this.getSearchConfig(handleCol);
                if(handleConfig) {
                    outConfig.push(handleConfig);
                }
                return outConfig;
            }
            return filterFormConfig;
        },
        permission() {
            return function(config) {
                let permission = config.permission;
                if(!permission) {
                    return "";
                }
                if(typeof permission === 'string') {
                        return {
                            key: permission,
                            label: config.name,
                        }
                }else {
                    return config.permission;
                }
            };
        },
        hasSelection() {
            return Boolean(
                (this.tableColumn || []).filter(v => v.type === "select").length
            );
        },
        hasTopOperationLeft() {
            return (
                this.topOperation &&
                this.topOperation.left &&
                this.topOperation.left.length
            );
        }
    },
    mounted() {
        if(this.autoLoad) {
            this.$nextTick(() => {
                this.filterFormQueryHandle();
            })
        }
    },
    methods: {
         // 得到一个查询操作按钮
         getSearchConfig(col) {
            if(this.showSearch) {
                const _this = this
                return {
                    key: "$handleSlot", // 操作插槽位置，获取数据的时候要把这个删除
                    col: col,
                    noLabel: true,
                    type: 'render',
                    render: (h) => {
                        return (
                            <div class="w-100" style="text-align: right">
                                <el-button type="primary" v-permission={this.busCode} on-click={()=>this.operationHandle({ handle: 'query' })} size="mini">查询</el-button>
                                {
                                    this.filterFormConfig 
                                    ? <el-button v-permission={this.busCode} on-click={()=>this.operationHandle({ handle: 'resetFilterForm' })} type="default" size="mini">重置</el-button>
                                    : null
                                }
                                {   this.closeNumber
                                    ? (
                                        <span class="coll_control mx-12" on-click={(v) => (this.showColl = !this.showColl)}>
                                            { this.showColl ? "收起" : "展开" }
                                            <i class="el-icon-d-arrow-right"></i>
                                        </span>
                                      )
                                    : ''
                                }
                                

                            </div>
                        )
                        
                    }
                }
            }
        },
        operationHandle(operation = {}) {

            let handleArguments = [];

            if (
                operation.requireArguments &&
                operation.requireArguments.length
            ) {
                operation.requireArguments.forEach(argumentItem => {
                    handleArguments.push(
                        this.handleArgumentMap[argumentItem]()
                    );
                });
            }
            if (operation.handle) {
                if (typeof operation.handle === "string") {
                    if (operation.handle === "query" && this.searchEmit) {
                        return this.$emit("searchEmit");
                    }
                    if (this.resetHandle&&operation.handle=='resetFilterForm'){
                        this.resetHandle()
                    }
                   let stringHandleMap= this.stringHandleMap[operation.handle](
                        ...handleArguments
                    );
                    if (this.resetOut&&operation.handle=='resetFilterForm'){
                        this.resetOut()
                    }
                    return stringHandleMap
                } else if (typeof operation.handle === "function") {
                    return operation.handle(...handleArguments);
                }
            }
        },
        getFormData() {
            let formData = {
                ...this.$refs.filterForm.formData
            };
            delete formData.$handleSlot;
            return formData;
        },
        setFormData(data) {
            let ref = this.$refs.filterForm;
            ref && ref.setFormData(data);
        },
        resetFilterForm({fetchData = true} = {}) {
            this.$refs.table.setPagerNumber(1, 10);
            this.$refs.filterForm.resetFields();
            if(fetchData) {
                this.filterFormQueryHandle();
            }
        },
        async validateFilterForm() {
            return new Promise((resovle, reject) => {
                let ref = this.$refs.filterForm;
                ref &&
                    ref.validate((success, error) => {
                        if (success) {
                            resovle(ref.formData);
                        } else {
                            reject(error);
                        }
                    });
            });
        },
        // 获取格式化后的数据
        getHandleFormData() {
            let formData = {
                ...(this.$refs?.filterForm?.formData || {}),
                ...this.params
            };
            delete formData.$handleSlot; // 删除没用的key
        
            (this.$refs?.filterForm?.configData || []).forEach(item => {
                const key = item.key;

                if (!formData[key] && formData[key] !== 0) {
                    delete formData[key];
                }

                if (typeof formData[key] === "string") {
                    formData[key] = formData[key].trim();
                }
                const defaultFormat = {
                    datetimerange: 'yyyy-MM-DD HH:mm:ss',
                    datetime: 'yyyy-MM-DD HH:mm:ss',
                    daterange: 'yyyy-MM-DD',
                    date: 'yyyy-MM-DD',
                    time: 'HH:mm:ss'
                }
                let timeFormat = item.timeFormat || defaultFormat[item.type];
                if (
                    formData[key] &&
                    (item.type === "daterange" ||
                        item.type === "datetimerange" || item.type === 'time') &&
                    item.keyRange
                ) {
                        // item.timeFormat ||
                        // (item.type === "datetimerange"
                        //     ? "yyyy-MM-DD HH:mm:ss"
                        //     : "yyyy-MM-DD");
                    formData[item.keyRange[0]] = formatDate(formData[key][0], timeFormat);
                    formData[item.keyRange[1]] = formatDate(formData[key][1], timeFormat);
                    delete formData[key];
                }
                if (
                    formData[key] &&
                    (item.type === "date" || item.type === "datetime")
                ) {
                    formData[key] =
                        typeof formData[key] !== "string"
                            ? formatDate(formData[key], timeFormat)
                            : formData[key];
                }
            });
            return formData;
        },
        async filterFormQueryHandle() {
            if(this.showFormFilter) {
                let success = await new Promise(resovle => {
                    let ref = this.$refs.filterForm;
                    ref &&
                        ref.validate(success => {
                            if (success) {
                                resovle(true);
                            } else {
                                resovle(false);
                            }
                        });
                });
                if (!success) {
                    return;
                }
            }

            let formData = this.getHandleFormData();
            if (this.queryDataHandle) {
                formData = await this.queryDataHandle(formData);
                if (!formData){
                    //中断提交
                    return
                }
            }

            this.filteData = formData;

            this.$nextTick(() => {
                this.refetch();
            });
        },
        refetch() {
            let result = true;

            if(this.beforeSearch) {
                result = this.beforeSearch(this.filteData);
            }
            if(!result) {
                return;
            }
            if(!result.then) {
                return this.debounce.run(() => this.$refs.table.request());
            }
            
            result.then((flag) => {
                flag && (this.debounce.run(() => this.$refs.table.request()))
            })
            // this.$refs.table.request();
        },
        tableSelectionChangeHandle(list) {
            this.selectionList = list;
            this.$emit('selected-change', list);
        },
        selectAll(list){
            this.$emit('selected-change', list);
        },
        selectHandle(list){
            this.$emit('select', list);
        },
        tableDataChange(data) {
            this.tableData = data;
            this.$emit("data-change", data);
        },
        tableCurrentChangeHandle(currentRow, oldCurrentRow) {
            this.$emit("current-change", currentRow, oldCurrentRow);
        },
        getLastQueryParams() {
            if (!this.$refs.table) {
                return null;
            }
            return this.$refs.table.lastQueryParams;
        },
        getRadioSelect() {
            return this.$refs.table.radioSelect;
        }
    }
};
